<?php
/**
 * Created by PhpStorm.
 * User: TS
 * Date: 2017/4/4
 * Time: 20:26
 */
namespace core;

use core\http\Request;

class Url {

    protected static $instance = null;


    /**
     * @return null|static
     */
    public static function getInstance()
    {
        if (is_null(self::$instance)) {
            self::$instance = new static();
        }
        return self::$instance;
    }

    /**
     * parse mvc
     * @param $url
     * @return array
     */
    public static function parseUrl(&$url)
    {

        $params = explode('/', $url);
        $module = $controller = $action = 'index';
        if (!empty($params) && !empty(next($params))) {
            unset($params[0]);
            $module = array_shift($params);
            $controllerLevel = Config::get('controller_level') ?: '1';

            if (!empty($params)) {
                $controller = [];
                for($i = 0; $i < $controllerLevel; $i++) {
                    $controller[] = array_shift($params);
                }
                if (!empty($controller)) $controller = implode('\\', $controller);
            }
            if (!empty($params)) $action = array_shift($params);

            if (!empty($params)) {
                $getParams = array_chunk($params, 2);
                if (!empty($getParams)) foreach ($getParams as $v) {
                    list($name, ) = $v;
                    $value = isset($v['1']) ? $v['1'] : null;
                    Request::getInstance()->set($name, $value);
                }

            }
        }

        return (array('m' => $module, 'c' => $controller, 'a' => $action));
    }


}